//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dataview_dao

import (
	"context"
	"sort"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/dataview_chat_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ChatMsgIndexDbItem struct {
	MsgId     string `bson:"_id"`
	ViewId    string `bson:"viewId"`
	TimeStamp int64  `bson:"timeStamp"`
}

type ChatMsgIndexList []*ChatMsgIndexDbItem

func (l ChatMsgIndexList) Len() int {
	return len(l)
}

func (l ChatMsgIndexList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l ChatMsgIndexList) Less(i, j int) bool {
	return l[i].TimeStamp < l[j].TimeStamp
}

type _ChatMsgIndexDao struct {
	mc *mongo.Collection
}

func newChatMsgIndexDao(db *mongo.Database) (*_ChatMsgIndexDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_DATAVIEW + "chat_msg_index")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"viewId", 1}, {"timeStamp", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ChatMsgIndexDao{mc: mc}, nil
}

func (db *_ChatMsgIndexDao) Insert(ctx context.Context, dbItem *ChatMsgIndexDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ChatMsgIndexDao) Exist(ctx context.Context, msgId, viewId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": msgId, "viewId": viewId})
	return count > 0, err
}

func (db *_ChatMsgIndexDao) GetListMsgId(ctx context.Context, viewId string) (string, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"viewId": viewId}, options.Find().SetLimit(1).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return "", err
	}
	tmpList := []*ChatMsgIndexDbItem{}
	err = cursor.All(ctx, &tmpList)
	if err != nil {
		return "", err
	}
	if len(tmpList) == 0 {
		return "", nil
	}
	return tmpList[0].MsgId, nil
}

func (db *_ChatMsgIndexDao) List(ctx context.Context, viewId string, listType dataview_chat_api.LIST_TYPE, listRefTime, limit int64) ([]*ChatMsgIndexDbItem, error) {
	query := bson.M{"viewId": viewId}
	sortOrder := 1
	if listType == dataview_chat_api.LIST_TYPE_LIST_TYPE_BEFORE {
		query["timeStamp"] = bson.M{"$lt": listRefTime}
		sortOrder = -1
	} else {
		query["timeStamp"] = bson.M{"$gt": listRefTime}
	}
	cursor, err := db.mc.Find(ctx, query, options.Find().SetLimit(limit).SetSort(bson.M{"timeStamp": sortOrder}))
	if err != nil {
		return nil, err
	}
	retList := []*ChatMsgIndexDbItem{}
	err = cursor.All(ctx, &retList)
	if err != nil {
		return nil, err
	}
	sort.Sort(ChatMsgIndexList(retList))
	return retList, nil
}
